package com.twu.biblioteca.System;

import com.twu.biblioteca.Models.Data;
import com.twu.biblioteca.Models.User;

import java.util.InputMismatchException;
import java.util.Scanner;

/**
 * Created by ubuntu on 4/30/14.
 */
public class Login {
    private Data data;

    public Login(Data data) {
        this.data = data;
    }

    Scanner scanner = new Scanner(System.in);

    public boolean authenticate() {
        String userId = getUserId();
        String password = getPassword();
        return verifyUser(userId, password);
    }

    private String getPassword() {
        String password;
        System.out.println("Enter the password");
        password = scanner.next();
        return password;
    }

    private String getUserId() {
        String userId = null;
        System.out.println("Login:");
        System.out.println("Enter your user Id xx-xxx:");
        try {
            userId = scanner.next("\\w{2}-\\w{3}");
        } catch (InputMismatchException ime) {
            System.out.println("Please Enter correct ID");
        }
        return userId;
    }

    private boolean verifyUser(String userId, String password) {
        if (userId != null && password != null) {
            User user = data.searchUserById(userId);
            if (user != null && user.verifyPassword(password)) {
                data.setLoggedInUser(user);
                return true;
            }
        }
        return false;
    }

}
